<%@ page autoFlush="false"
	import="java.awt.*,java.awt.image.*,com.sun.image.codec.jpeg.*,java.util.*"
	pageEncoding="utf-8"%>

<%
	//set Chinese Char 
	//Cody by JarryLi@gmail.com;
	//homepage:jiarry.126.com
	request.setCharacterEncoding("GBK");
	response.setCharacterEncoding("GBK");
	response.setContentType("text/html; charset=GBK");
%>
<%
	String chose = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

	char display[] = { '0', ' ', '0', ' ', '0', ' ', '0' }, ran[] = {
			'0', '0', '0', '0' }, temp;
	Color colors[]={Color.red,Color.blue,Color.MAGENTA,Color.GRAY,Color.green,Color.LIGHT_GRAY,Color.BLACK,Color.cyan,Color.ORANGE,Color.pink};
	Random rand = new Random();

	for (int i = 0; i < 4; i++) {

		temp = chose.charAt(rand.nextInt(chose.length()));

		display[i * 2] = temp;

		ran[i] = temp;
	}

	String random = String.valueOf(display);
	//将随机产生的字符放入session范围的变量random中
	session.setAttribute("random", String.valueOf(ran));

	out.clear();
	response.setContentType("image/jpeg");
	response.addHeader("pragma", "NO-cache");
	response.addHeader("Cache-Control", "no-cache");
	response.addDateHeader("Expries", 0);
	int width = 80, height = 22;
	BufferedImage image = new BufferedImage(width, height,
			BufferedImage.TYPE_INT_RGB);
	Graphics g = image.getGraphics();
	//以下填充背景颜色
	g.setColor(Color.WHITE);
	g.fillRect(0, 0, width, height);
	Font font = new Font("Arial", Font.PLAIN, 18);
	g.setFont(font);
	char[] word=random.toCharArray();
	//设置字体颜色
	for(int i=0;i<word.length;i++){
		g.setColor(colors[rand.nextInt(colors.length)]);
		g.drawString(String.valueOf(word[i]), 5+10*i, 18);
	}
	g.setColor(Color.gray);
	// 随机产生4条线，使图象中的认证码不易被其它程序探测到  By.Tudou
	for (int i = 0; i < 4; i++) {
		int x = rand.nextInt(width);
		int y = rand.nextInt(height);
		int x1 = rand.nextInt(width);
		int y1 = rand.nextInt(height);
		g.drawLine(x, y, x1, y1);
	}
	// 随机产生50个干扰点，使图象中的认证码不易被其它程序探测到 
	for (int i = 0; i < 50; i++) {
		int x = rand.nextInt(width);
		int y = rand.nextInt(height);
		g.drawOval(x, y, 0, 0);
	}

	g.dispose();
	ServletOutputStream outStream = response.getOutputStream();
	JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream);
	encoder.encode(image);
	outStream.close();
	out.clear();
	out = pageContext.pushBody();
%>
